home *** CD-ROM | disk | FTP | other *** search
/ Aminet 1 (Walnut Creek) / Aminet - June 1993 [Walnut Creek].iso / aminet / util / gnu / textutl3.lha / textutils-1.3 / src / unexpand.c < prev    next >
C/C++ Source or Header  |  1992-06-29  |  10KB  |  433 lines

  1. /* unexpand - convert spaces to tabs
  2.    Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* By default, convert only maximal strings of initial blanks and tabs
  19.    into tabs.
  20.    Preserves backspace characters in the output; they decrement the
  21.    column count for tab calculations.
  22.    The default action is equivalent to -8.
  23.  
  24.    Options:
  25.    --tabs=tab1[,tab2[,...]]
  26.    -t tab1[,tab2[,...]]
  27.    -tab1[,tab2[,...]]    If only one tab stop is given, set the tabs tab1
  28.             spaces apart instead of the default 8.  Otherwise,
  29.             set the tabs at columns tab1, tab2, etc. (numbered from
  30.             0); replace any tabs beyond the tabstops given with
  31.             single spaces.
  32.    --all
  33.    -a            Use tabs wherever they would replace 2 or more spaces,
  34.             not just at the beginnings of lines.
  35.  
  36.    David MacKenzie <djm@ai.mit.edu> */
  37.  
  38. #define _GNU_SOURCE
  39. #include <ctype.h>
  40. #ifndef isblank
  41. #define isblank(c) ((c) == ' ' || (c) == '\t')
  42. #endif
  43. #include <stdio.h>
  44. #include <getopt.h>
  45. #include <sys/types.h>
  46. #include "system.h"
  47.  
  48. #ifdef isascii
  49. #define ISDIGIT(c) (isascii((c)) && isdigit((c)))
  50. #else
  51. #define ISDIGIT(c) (isdigit((c)))
  52. #endif
  53.  
  54. /* The number of bytes added at a time to the amount of memory
  55.    allocated for the output line. */
  56. #define OUTPUT_BLOCK 256
  57.  
  58. /* The number of bytes added at a time to the amount of memory
  59.    allocated for the list of tabstops. */
  60. #define TABLIST_BLOCK 256
  61.  
  62. char *xmalloc ();
  63. char *xrealloc ();
  64. void error ();
  65.  
  66. FILE *next_file ();
  67. void add_tabstop ();
  68. void parse_tabstops ();
  69. void unexpand ();
  70. void usage ();
  71. void validate_tabstops ();
  72.  
  73. /* If nonzero, convert blanks even after nonblank characters have been
  74.    read on the line. */
  75. int convert_entire_line;
  76.  
  77. /* If nonzero, the size of all tab stops.  If zero, use `tab_list' instead. */
  78. int tab_size;
  79.  
  80. /* Array of the explicit column numbers of the tab stops;
  81.    after `tab_list' is exhausted, the rest of the line is printed
  82.    unchanged.  The first column is column 0. */
  83. int *tab_list;
  84.  
  85. /* The index of the first invalid element of `tab_list',
  86.    where the next element can be added. */
  87. int first_free_tab;
  88.  
  89. /* Null-terminated array of input filenames. */
  90. char **file_list;
  91.  
  92. /* Default for `file_list' if no files are given on the command line. */
  93. char *stdin_argv[] =
  94. {
  95.   "-", NULL
  96. };
  97.  
  98. /* Nonzero if we have ever read standard input. */
  99. int have_read_stdin;
  100.  
  101. /* Status to return to the system. */
  102. int exit_status;
  103.  
  104. /* The name this program was run with. */
  105. char *program_name;
  106.  
  107. struct option longopts[] =
  108. {
  109.   {"tabs", 1, NULL, 't'},
  110.   {"all", 0, NULL, 'a'},
  111.   {NULL, 0, NULL, 0}
  112. };
  113.  
  114. void
  115. main (argc, argv)
  116.      int argc;
  117.      char **argv;
  118. {
  119.   int tabval = -1;        /* Value of tabstop being read, or -1. */
  120.   int c;            /* Option character. */
  121.  
  122.   have_read_stdin = 0;
  123.   exit_status = 0;
  124.   convert_entire_line = 0;
  125.   tab_list = NULL;
  126.   first_free_tab = 0;
  127.   program_name = argv[0];
  128.  
  129.   while ((c = getopt_long (argc, argv, "at:,0123456789", longopts, (int *) 0))
  130.      != EOF)
  131.     {
  132.       switch (c)
  133.     {
  134.     case '?':
  135.       usage ();
  136.     case 'a':
  137.       convert_entire_line = 1;
  138.       break;
  139.     case 't':
  140.       convert_entire_line = 1;
  141.       parse_tabstops (optarg);
  142.       break;
  143.     case ',':
  144.       add_tabstop (tabval);
  145.       tabval = -1;
  146.       break;
  147.     default:
  148.       if (tabval == -1)
  149.         tabval = 0;
  150.       tabval = tabval * 10 + c - '0';
  151.       break;
  152.     }
  153.     }
  154.  
  155.   add_tabstop (tabval);
  156.  
  157.   validate_tabstops (tab_list, first_free_tab);
  158.  
  159.   if (first_free_tab == 0)
  160.     tab_size = 8;
  161.   else if (first_free_tab == 1)
  162.     tab_size = tab_list[0];
  163.   else
  164.     tab_size = 0;
  165.  
  166.   if (optind == argc)
  167.     file_list = stdin_argv;
  168.   else
  169.     file_list = &argv[optind];
  170.  
  171.   unexpand ();
  172.  
  173.   if (have_read_stdin && fclose (stdin) == EOF)
  174.     error (1, errno, "-");
  175.   if (fclose (stdout) == EOF)
  176.     error (1, errno, "write error");
  177.   exit (exit_status);
  178. }
  179.  
  180. /* Add the comma or blank separated list of tabstops STOPS
  181.    to the list of tabstops. */
  182.  
  183. void
  184. parse_tabstops (stops)
  185.      char *stops;
  186. {
  187.   int tabval = -1;
  188.  
  189.   for (; *stops; stops++)
  190.     {
  191.       if (*stops == ',' || isblank (*stops))
  192.     {
  193.       add_tabstop (tabval);
  194.       tabval = -1;
  195.     }
  196.       else if (ISDIGIT (*stops))
  197.     {
  198.       if (tabval == -1)
  199.         tabval = 0;
  200.       tabval = tabval * 10 + *stops - '0';
  201.     }
  202.       else
  203.     error (1, 0, "tab size contains an invalid character");
  204.     }
  205.  
  206.   add_tabstop (tabval);
  207. }
  208.  
  209. /* Add tab stop TABVAL to the end of `tab_list', except
  210.    if TABVAL is -1, do nothing. */
  211.  
  212. void
  213. add_tabstop (tabval)
  214.      int tabval;
  215. {
  216.   if (tabval == -1)
  217.     return;
  218.   if (first_free_tab % TABLIST_BLOCK == 0)
  219.     tab_list = (int *) xrealloc (tab_list, first_free_tab + TABLIST_BLOCK);
  220.   tab_list[first_free_tab++] = tabval;
  221. }
  222.  
  223. /* Check that the list of tabstops TABS, with ENTRIES entries,
  224.    contains only nonzero, ascending values. */
  225.  
  226. void
  227. validate_tabstops (tabs, entries)
  228.      int *tabs;
  229.      int entries;
  230. {
  231.   int prev_tab = 0;
  232.   int i;
  233.   
  234.   for (i = 0; i < entries; i++)
  235.     {
  236.       if (tabs[i] == 0)
  237.     error (1, 0, "tab size cannot be 0");
  238.       if (tabs[i] <= prev_tab)
  239.     error (1, 0, "tab sizes must be ascending");
  240.       prev_tab = tabs[i];
  241.     }
  242. }
  243.  
  244. /* Change spaces to tabs, writing to stdout.
  245.    Read each file in `file_list', in order. */
  246.  
  247. void
  248. unexpand ()
  249. {
  250.   FILE *fp;            /* Input stream. */
  251.   int c;            /* Each input character. */
  252.   /* Index in `tab_list' of next tabstop: */  
  253.   int tab_index = 0;        /* For calculating width of pending tabs. */
  254.   int print_tab_index = 0;    /* For printing as many tabs as possible. */
  255.   int column = 0;        /* Column on screen of next char. */
  256.   int next_tab_column;         /* Column the next tab stop is on. */
  257.   int convert = 1;        /* If nonzero, perform translations. */
  258.   int pending = 0;        /* Pending columns of blanks. */
  259.  
  260.   fp = next_file ((FILE *) NULL);
  261.   for (;;)
  262.     {
  263.       c = getc (fp);
  264.       if (c == EOF)
  265.     {
  266.       fp = next_file (fp);
  267.       if (fp == NULL)
  268.         break;        /* No more files. */
  269.       else
  270.         continue;
  271.     }
  272.  
  273.       if (c == ' ' && convert)
  274.     {
  275.       ++pending;
  276.       ++column;
  277.     }
  278.       else if (c == '\t' && convert)
  279.     {
  280.       if (tab_size == 0)
  281.         {
  282.           /* Do not let tab_index == first_free_tab;
  283.          stop when it is 1 less. */
  284.           while (tab_index < first_free_tab - 1
  285.              && column >= tab_list[tab_index])
  286.         tab_index++;
  287.           next_tab_column = tab_list[tab_index];
  288.           if (tab_index < first_free_tab - 1)
  289.         tab_index++;
  290.           if (column >= next_tab_column)
  291.         {
  292.           convert = 0;    /* Ran out of tab stops. */
  293.           goto flush_pend;
  294.         }
  295.         }
  296.       else
  297.         {
  298.           next_tab_column = column + tab_size - column % tab_size;
  299.         }
  300.       pending += next_tab_column - column;
  301.       column = next_tab_column;
  302.     }
  303.       else
  304.     {
  305.     flush_pend:
  306.       /* Flush pending spaces.  Print as many tabs as possible,
  307.          then print the rest as spaces. */
  308.       if (pending == 1)
  309.         {
  310.           putchar (' ');
  311.           pending = 0;
  312.         }
  313.       column -= pending;
  314.       while (pending != 0)
  315.         {
  316.           if (tab_size == 0)
  317.         {
  318.           /* Do not let tab_index == first_free_tab;
  319.              stop when it is 1 less. */
  320.           while (tab_index < first_free_tab - 1
  321.              && column >= tab_list[tab_index])
  322.             print_tab_index++;
  323.           next_tab_column = tab_list[print_tab_index];
  324.           if (print_tab_index < first_free_tab - 1)
  325.             print_tab_index++;
  326.         }
  327.           else
  328.         {
  329.           next_tab_column = column + tab_size - column % tab_size;
  330.         }
  331.           if (next_tab_column - column <= pending)
  332.         {
  333.           putchar ('\t');
  334.           pending -= next_tab_column - column;
  335.           column = next_tab_column;
  336.         }
  337.           else
  338.         {
  339.           --print_tab_index;
  340.           column += pending;
  341.           while (pending != 0)
  342.             {
  343.               putchar (' ');
  344.               pending--;
  345.             }
  346.         }
  347.         }
  348.  
  349.       if (convert)
  350.         {
  351.           if (c == '\b')
  352.         {
  353.           if (column > 0)
  354.             --column;
  355.         }
  356.           else
  357.         {
  358.           ++column;
  359.           if (convert_entire_line == 0)
  360.             convert = 0;
  361.         }
  362.         }
  363.  
  364.       putchar (c);
  365.  
  366.       if (c == '\n')
  367.         {
  368.           tab_index = print_tab_index = 0;
  369.           column = pending = 0;
  370.           convert = 1;
  371.         }
  372.     }
  373.     }
  374. }
  375.  
  376. /* Close the old stream pointer FP if it is non-NULL,
  377.    and return a new one opened to read the next input file.
  378.    Open a filename of `-' as the standard input.
  379.    Return NULL if there are no more input files.  */
  380.  
  381. FILE *
  382. next_file (fp)
  383.      FILE *fp;
  384. {
  385.   static char *prev_file;
  386.   char *file;
  387.  
  388.   if (fp)
  389.     {
  390.       if (ferror (fp))
  391.     {
  392.       error (0, errno, "%s", prev_file);
  393.       exit_status = 1;
  394.     }
  395.       if (fp == stdin)
  396.     clearerr (fp);        /* Also clear EOF. */
  397.       else if (fclose (fp) == EOF)
  398.     {
  399.       error (0, errno, "%s", prev_file);
  400.       exit_status = 1;
  401.     }
  402.     }
  403.  
  404.   while ((file = *file_list++) != NULL)
  405.     {
  406.       if (file[0] == '-' && file[1] == '\0')
  407.     {
  408.       have_read_stdin = 1;
  409.       prev_file = file;
  410.       return stdin;
  411.     }
  412.       fp = fopen (file, "r");
  413.       if (fp)
  414.     {
  415.       prev_file = file;
  416.       return fp;
  417.     }
  418.       error (0, errno, "%s", file);
  419.       exit_status = 1;
  420.     }
  421.   return NULL;
  422. }
  423.  
  424. void
  425. usage ()
  426. {
  427.   fprintf (stderr, "\
  428. Usage: %s [-tab1[,tab2[,...]]] [-t tab1[,tab2[,...]]] [-a]\n\
  429.        [--tabs=tab1[,tab2[,...]]] [--all] [file...]\n",
  430.        program_name);
  431.   exit (1);
  432. }
  433.